package com.bobbygu.bobbyapp.function.upload

import android.Manifest
import android.graphics.Bitmap
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import com.bobbygu.lib.mvvm.common.BaseActivity
import com.bobbygu.bobbyapp.R
import com.tbruyelle.rxpermissions2.Permission
import com.tbruyelle.rxpermissions2.RxPermissions


/**
 *
 * # time:   2017/10/23 16:53
 * # e-mail: gubojun@csii.com.cn
 * @author 顾博君
 * @since
 */
class UploadActivity : BaseActivity<UploadViewModel, UploadModel>(), UploadContract.View {
    var img: ImageView? = null
    var rxPermiessions: RxPermissions? = null
    override fun getLayoutId() = R.layout.activity_upload
    override fun getBR() = 0
    override fun initView() {
        img = findViewById(R.id.img)
        rxPermiessions = RxPermissions(this)
    }

    override fun returnBitmap(bitmap: Bitmap) {
        img?.setImageBitmap(bitmap)
    }

    fun View.uploadFile() {
        if (rxPermiessions != null && !rxPermiessions!!.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            rxPermiessions!!.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe({
                        fun accept(permission: Permission) = when {
                            permission.granted -> // 用户已经同意该权限
                                viewModel.uploadFile()
                            permission.shouldShowRequestPermissionRationale -> // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                                Toast.makeText(this@UploadActivity, "未通过申请", Toast.LENGTH_LONG).show()
                            else -> // 用户拒绝了该权限，并且选中『不再询问』
                                Toast.makeText(this@UploadActivity, "未通过申请", Toast.LENGTH_LONG).show()
                        }
                    })
        } else
            viewModel.uploadFile()
    }

    fun View.getImg() = viewModel.getImg()

    companion object {

        /**
         * @param activity BaseActivity
         */
        fun startActivity(activity: BaseActivity<*, *>) {
            activity.startActivity(UploadActivity::class.java)
        }
    }
}